<?php

namespace App\Exports;


use App\Models\Flight\Order;
use App\Models\Rbac\GuardUser;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class DemoExport extends CommonExport
{
    public function __construct(array $conditions=[],array $params=[]) {
        $this->instance = (new Order());
        $this->conditions = $conditions;
        $this->params = $params;
        $this->title = [
            'ID',
            '记录编码',
            '航班号',
            '乘客姓名',
            '护照号',
            '乘客性别',
            '乘客生日',
            '乘客类型',
            '出发日期',
            '起飞时间',
            '降落时间',
            '起飞地点',
            '降落地点',
            '录入时间',
            '录入人员',
            '备注信息',
        ];


    }

    public function array(): array {
        $this->records = [$this->title];
        $cols = [
            'id',
            'code',
            'name',
            'passport',
            'passenger_sex',
            'passenger_birthday',
            'passenger_type',
            'flight_id',
            'writer_id',
            'beizhu',
            'created_at',
        ];

        $this->records = $this->instance->getLst($this->conditions)->with(['getFlightInfo'])->get($cols);
        $mapUsers = GuardUser::pluck('name','id')->toArray();

        $data = [];
        foreach ($this->records as $record) {
            $data[] = [
                $record->id,
                $record->code,
                $record->getFlightInfo->flight_no,
                $record->name,
                $record->passport,
                $record->passenger_sex=='M'?'男':'女',
                $record->passenger_birthday,
                getPassagerType($record->passenger_birthday),
                $record->getFlightInfo->date,
                $record->getFlightInfo->start_fly_time,
                $record->getFlightInfo->end_fly_time,
                $record->getFlightInfo->start_airport,
                $record->getFlightInfo->end_airport,
                $record->created_at,
                $mapUsers[$record->writer_id]??'未知',
                $record->beizhu,
            ];
            unset($record->getFlightInfo);
        }

        $this->records = $this->records->toArray();

        array_unshift($data,$this->title);
        return $data;
    }

    public function bindValue(Cell $cell, $value) {
        if (is_string($value) && strlen($value) > 10) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }

}
